var models = require('../models');
var multiparty = require('multiparty');
var utils = require('../utils');
var consts = require('../consts');

/**
 * Created by banzhenyu on 2016/10/28.
 * 用户登陆相关的逻辑
 */
var functions = {

    /**
     * 管理员登录
     * @param req
     * @param res
     * @param next
     */
    login: function (req, res, next) {
        let login_name = req.body.login_name;
        let password = req.body.password;
        var condition = {login_name: login_name};

        models.mysql.Users.findOne({where: condition}).then(function (user) {
            if (user) {
                //websit---> md5pwd ----> node --->((key)+md5pwd)+盐--->db
                var md5_pwd = utils.md5utils.md5(consts.MD5_KEY + password);
                if (user.password == md5_pwd) { //判断条件 登录成功
                    var tk = utils.md5utils.md5(login_name+password+new Date().getTime()); //MD5(userid + pwd + time)
                    console.log("generate token : %s",tk);
                    models.tokenCache.putLoginToken(login_name,tk);
                    res.json({code: 0, data: {login_name: login_name, token: tk}});
                } else {
                    res.json({code: 1, message: "密码有误!"});
                }
            } else {
                res.json({code: 1, message: "无此账号!"});
            }
        }).catch(function (ex) {
            res.json({code: 1, message: ex.toString()});
        })
    },

    /**
     * 退出登录
     * @param req
     * @param res
     * @param next
     */
    logout: function (req, res, next) {
        let login_name = req.query.login_name;
        models.tokenCache.removeLoginToken(req.query.token);
        res.json({code: 1, message: "退出登录成功!"});
    }

};
module.exports = functions;
